package com.numericme.locale.switcher;

import java.util.List;

import org.acra.ErrorReporter;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;

import com.devoteam.quickaction.QuickActionWindow;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.numericme.locale.switcher.tools.ProMode;
import com.numericme.locale.switcher.tools.Tools;

public class QuickActionLauncher extends Activity {

	GoogleAnalyticsTracker tracker;
	
	private Context mContext = this;
	
	private View v1 = null;
	private QuickActionWindow qa;
	
    private boolean firstFocus = true;    
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.launcher_main);		
		
		v1 = (View) findViewById(R.id.View);
		
		Rect rect = new Rect(0, 0, 50, 50);

		String preftoUse = Tools.SHARED_PREFS_NAME;
		SharedPreferences prefs = QuickActionLauncher.this.getSharedPreferences(preftoUse, 0);
	    
		qa = new QuickActionWindow(mContext, v1, rect);

		boolean localeSwitcher = prefs.getBoolean(Tools.LOCALE_SWITCHER_KEY, Boolean.parseBoolean(getString(R.string.locale_switcher_pref_def_value)));
		boolean rotation = prefs.getBoolean(Tools.ROTATION_KEY, Boolean.parseBoolean(getString(R.string.rotation_pref_def_value)));
		boolean wifi = prefs.getBoolean(Tools.WIFI_KEY, Boolean.parseBoolean(getString(R.string.wifi_pref_def_value)));
		boolean display = prefs.getBoolean(Tools.DISPLAY_KEY, Boolean.parseBoolean(getString(R.string.display_pref_def_value)));
		boolean sound = prefs.getBoolean(Tools.SOUND_KEY, Boolean.parseBoolean(getString(R.string.sound_pref_def_value)));
		boolean systemSettings = prefs.getBoolean(Tools.SYSTEM_SETTINGS_KEY, Boolean.parseBoolean(getString(R.string.system_settings_pref_def_value)));
		boolean instantToolsSettings = prefs.getBoolean(Tools.INSTANT_TOOLS_PREFERENCES_KEY, Boolean.parseBoolean(getString(R.string.instant_tools_preferences_pref_def_value)));
		
		if(localeSwitcher) {
			qa.addItem(getResources().getDrawable(R.drawable.tools_locale), getString(R.string.locale_switcher_displayed_title), new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.setPackage("com.android.settings");
					intent.setClassName("com.android.settings", "com.android.settings.LocalePicker");
					startActivitiesSafely(intent);

					((Activity) mContext).finish();
				}
			}, null);
		}
		
		if(rotation) {
			int status = -1;
			status = Settings.System.getInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 2);
			
			if(status==1) {
				qa.addItem(getResources().getDrawable(R.drawable.disable_rotation), getString(R.string.rotation_disable_displayed_title), new OnClickListener() {
					public void onClick(View v) {
						Settings.System.putInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 0);
												
						((Activity) mContext).finish();
					}
				}, null);
			}
			else if(status==0){
				qa.addItem(getResources().getDrawable(R.drawable.enable_rotation), getString(R.string.rotation_enable_displayed_title), new OnClickListener() {
					public void onClick(View v) {
						Settings.System.putInt(mContext.getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);

						((Activity) mContext).finish();
					}
				}, null);
			}
		}
				
		if(wifi) {
			qa.addItem(getResources().getDrawable(R.drawable.tools_wifi), getString(R.string.wifi_displayed_title), new OnClickListener() {
				public void onClick(View v) {
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.setPackage("com.android.settings");
					intent.setClassName("com.android.settings", "com.android.settings.wifi.WifiSettings");
					startActivitiesSafely(intent, new Intent(Settings.ACTION_WIRELESS_SETTINGS), new Intent(Settings.ACTION_WIFI_SETTINGS));
					
					((Activity) mContext).finish();
				}
			}, null);
		}
		
		if(display) {
			qa.addItem(getResources().getDrawable(R.drawable.tools_display), getString(R.string.display_displayed_title), new OnClickListener() {
				public void onClick(View v) {
					startActivitiesSafely(new Intent(Settings.ACTION_DISPLAY_SETTINGS));
					
					((Activity) mContext).finish();
				}
			}, null);
		}
		if(sound) {
			qa.addItem(getResources().getDrawable(R.drawable.tools_sound), getString(R.string.sound_displayed_title), new OnClickListener() {
				public void onClick(View v) {
					startActivitiesSafely(new Intent(Settings.ACTION_SOUND_SETTINGS));
					
					((Activity) mContext).finish();
				}
			}, null);
		}
		if(systemSettings){
			qa.addItem(getResources().getDrawable(R.drawable.tools_android_settings), getString(R.string.system_settings_displayed_title), new OnClickListener() {
				public void onClick(View v) {
					startActivitiesSafely(new Intent(Settings.ACTION_SETTINGS));

					((Activity) mContext).finish();
				}
			}, null);
		}

		if(instantToolsSettings){
			qa.addItem(getResources().getDrawable(R.drawable.tools_preferences), getString(R.string.instant_tools_preferences_displayed_title), new OnClickListener() {
				public void onClick(View v) {
					launchSettings();

					((Activity) mContext).finish();
				}
			}, null);			
		}
		
		if(savedInstanceState == null){
			
		    tracker = GoogleAnalyticsTracker.getInstance();	    
		    // Start the tracker in manual dispatch mode...
		    tracker.start("UA-XXXXXXXX-X", this);
		    
			if(!ProMode.isInProMode(this)){

				tracker.trackPageView("/LauncherLocalePickerLite");
				tracker.dispatch();				
			}
			else{
				tracker.trackPageView("/LauncherLocalePickerPro");
				tracker.dispatch();
			}
		}
	}	

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if(hasFocus && firstFocus){
			qa.show();			
			firstFocus = false;			
		}
		else if(hasFocus){
			this.finish();
		}
	}

	@Override
	protected void onStop() {
		try{
			qa.dismiss();
		}
		catch(Exception e) {			
		}
		super.onStop();
	}

    @Override
	protected void onDestroy() {
		super.onDestroy();		
	} 
    
    private void launchSettings() {
		tracker.trackPageView("/Settings");
        // Manually start a dispatch.
		tracker.dispatch();
		
    	final Intent settingsIndent = new Intent(QuickActionLauncher.this, SettingsActivity.class);
		startActivity(settingsIndent);
		
	}
    
	public boolean startActivitiesSafely(Intent... intents) {
    	int size = intents.length;
    	for (int index=0; index<size; index++) {
    		try {
    			Intent intent = intents[index];
    			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    			startActivity(intent);
    			return true;
    		} catch (Exception e) {
    			ErrorReporter.getInstance().handleException(e);	
    		}
    	}
    	return false;
    }
	
    public boolean isServiceRunning(ActivityManager am,String nomService){          
        List<RunningServiceInfo> services = am.getRunningServices(100);        
        for(ActivityManager.RunningServiceInfo rsi:services){            
            if(rsi.process.equals(nomService)){                
                return true;
            }
        }
        return false;
    }
}
